import React, { useEffect, useRef } from "react";
import { Pie } from "@antv/g2plot";

const PieChart = () => {
  const chartRef = useRef(null); // 用于绑定 DOM 容器

  useEffect(() => {
    if (!chartRef.current) return; // 确保 ref 存在

    // 定义数据
    const data = [
        { key: '1', type: '简单报表',  count: 300, color: '#1677ff' },
        { key: '2', type: '表单',  count: 200, color: '#52c41a' },
        { key: '3', type: '静态页', count: 200, color: '#faad14' },
        { key: '4', type: '动态内容',  count: 200, color: '#722ed1' },
        { key: '5', type: '其他',  count: 100, color: '#eb2f96' },
      ];
    const totalCount = data.reduce((sum, item) => sum + item.count, 0);
    // 创建饼图实例\
    const piePlot = new Pie(chartRef.current, {
      appendPadding: 10,
      data,
      legend: false, // 关闭图例显示
      angleField: "count",
      colorField: "color",
      color: ({ color }) => color,
      radius: 0.8,          // 外半径（容器宽度的80%）
      innerRadius: 0.6,     // 内半径（外半径的60%）
      label: {
        type: "spider",
        offset: "-20%",
        content: ({ percent }) => `${(percent * 100).toFixed(0)}%`, //图上的文字 不是悬停。
        style: {
          fontSize: 14,
          textAlign: "center",
        },
      },
      statistic: {
        title: false,
        content: {
          customHtml: () => `
            <div style="text-align: center;">
              <div style="font-size: 20px; font-weight: normal;">页面数</div>
              <div style="font-size: 30px; margin-top: 10px;font-weight: bold;">${totalCount}</div>
            </div>
          `,
          style: {
            fontSize: 24,
            color: '#333',
            fontWeight: 'normal',
          },
        }
      },
      tooltip: { //控制悬停
        fields: ["type", "count"], // 需要显示的字段
        formatter: (datum) => {
          // 计算总和
          const total = data.reduce((sum, d) => sum + d.count, 0);
          // 计算百分比
          const percent = ((datum.count / total) * 100).toFixed(0) + "%";
          return {
            name: datum.type,
            value: percent, // 用百分比替代原本的count显示
          };
        },
      },
      interactions: [{ type: "element-active" }],
    });

    piePlot.render(); // 渲染饼图

    return () => piePlot.destroy(); // 组件卸载时销毁实例
  }, []);

  return <div ref={chartRef} style={{ width: "400px", height: "400px" }} />;
};

export default PieChart;
